/**
 * 
 */
package com.gmail.blackdog1987.carcare.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.Constant;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.activity.CarChangeTypeActivity;
import com.gmail.blackdog1987.carcare.activity.CarCleanActivity;
import com.gmail.blackdog1987.carcare.activity.CarFixTypeActivity;
import com.gmail.blackdog1987.carcare.activity.CarRentTypeActivity;
import com.gmail.blackdog1987.carcare.activity.CarSaleTypeActivity;
import com.gmail.blackdog1987.carcare.activity.DriveSchoolActivity;
import com.gmail.blackdog1987.carcare.activity.GasActivity;
import com.gmail.blackdog1987.carcare.activity.MeiRongActivity;
import com.gmail.blackdog1987.carcare.activity.OrderCleanActivity;
import com.gmail.blackdog1987.carcare.activity.OrderDriveCompanyActivity;
import com.gmail.blackdog1987.carcare.activity.PromotionJoinActivity;
import com.gmail.blackdog1987.carcare.activity.QRScanActivity;
import com.gmail.blackdog1987.carcare.activity.RoadHelpTypeActivity;
import com.gmail.blackdog1987.carcare.entity.TPromotion;
import com.gmail.blackdog1987.carcare.network.request.builder.CleanShopDetailRequestBuilder;
import com.gmail.blackdog1987.carcare.network.request.builder.PromotionRequestBuilder;
import com.gmail.blackdog1987.carcare.network.response.CleanShopDetailResponse;
import com.gmail.blackdog1987.carcare.network.response.IResponse;
import com.gmail.blackdog1987.carcare.network.response.PromotionResponse;
import com.gmail.blackdog1987.carcare.network.response.handler.CleanShopDetailResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.IResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.OnResponseListener;
import com.gmail.blackdog1987.carcare.network.response.handler.PromotionResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;

/**
 * @author wdy
 *
 */
public class HomeFragment extends Fragment implements OnClickListener, OnPageChangeListener, OnResponseListener {
	private View mContentView;
	private List<ImageView> imagelist = new ArrayList<ImageView>();
	private ViewPager viewPager;
	private boolean isStop = false;  //是否停止子线程  不会停止
	private Handler mHander;
	private static final int IMG_CHANGE = 1;
	private PromotionRequestBuilder mReq = new PromotionRequestBuilder();
	private PromotionResponseHandler mPicHander = new PromotionResponseHandler();
	private static final int REQUESTCODE_QR = 100;
	private CleanShopDetailRequestBuilder mCleanReq = new CleanShopDetailRequestBuilder();
	private CleanShopDetailResponseHandler mCleanHandler = new CleanShopDetailResponseHandler();

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mContentView = inflater.inflate(R.layout.fragment_home, null);
		reg();
		mHander = new Handler(){
			@Override
			public void handleMessage(android.os.Message msg) {
				switch(msg.what){
				case IMG_CHANGE:
					int newindex = viewPager.getCurrentItem() + 1;
					viewPager.setCurrentItem(newindex);
					break;
				default:
					break;
				}
			};
		};
		mReq.setPageIndex(1).setPageSize(4).postJsonRequest(getActivity(), mPicHander);
		return mContentView;
	};

	private void reg() {
		mContentView.findViewById(R.id.main_breakrule).setOnClickListener(this);
		mContentView.findViewById(R.id.main_carrent).setOnClickListener(this);
		mContentView.findViewById(R.id.main_carsale).setOnClickListener(this);
		mContentView.findViewById(R.id.main_change).setOnClickListener(this);
		mContentView.findViewById(R.id.main_clean).setOnClickListener(this);
		mContentView.findViewById(R.id.main_company).setOnClickListener(this);
		mContentView.findViewById(R.id.main_fix).setOnClickListener(this);
		mContentView.findViewById(R.id.main_gas).setOnClickListener(this);
		mContentView.findViewById(R.id.main_jiazhao).setOnClickListener(this);
		mContentView.findViewById(R.id.main_meirong).setOnClickListener(this);
		mContentView.findViewById(R.id.main_roadhelp).setOnClickListener(this);
		mContentView.findViewById(R.id.main_travle).setOnClickListener(this);
		mPicHander.setOnResponseListener(this);
		getActivity().findViewById(R.id.qr).setOnClickListener(this);
		mCleanHandler.setOnResponseListener(this);
	}
	
	private void initImg(){
		// 开启线程无限自动移动
		Thread myThread = new Thread(new Runnable() {

			@Override
			public void run() {
				while (!isStop&&viewPager.getChildCount()>1) {
					//每个两秒钟发一条消息到主线程，更新viewpager界面
					SystemClock.sleep(5000);
					mHander.sendEmptyMessage(IMG_CHANGE);
				}
			}
		});
		myThread.start(); // 用来更细致的划分  比如页面失去焦点时候停止子线程恢复焦点时再开启
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("MainScreen"); // 统计页面
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("MainScreen");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_breakrule:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CHECK) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CHECK) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
			break;
		case R.id.main_travle:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_TRAVEL) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_TRAVEL) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
			break;
		case R.id.main_clean:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CLEAN) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CLEAN) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), CarCleanActivity.class));
			break;
		case R.id.main_meirong:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_MAINTAIN) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_MAINTAIN) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), MeiRongActivity.class));
			break;
		case R.id.main_roadhelp:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_ROADHELP) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_ROADHELP) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), RoadHelpTypeActivity.class));
			break;
		case R.id.main_company:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_DRIVECOMPANY) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_DRIVECOMPANY) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), OrderDriveCompanyActivity.class));
			break;
		case R.id.main_gas:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_GAS) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_GAS) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), GasActivity.class));
			break;
		case R.id.main_carsale:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARSALE) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARSALE) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), CarSaleTypeActivity.class));
			break;
		case R.id.main_carrent:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARRENT) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARRENT) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), CarRentTypeActivity.class));
			break;
		case R.id.main_change:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARCHANGE) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARCHANGE) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), CarChangeTypeActivity.class));
			break;
		case R.id.main_fix:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARFIX) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_CARFIX) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), CarFixTypeActivity.class));
			break;
		case R.id.main_jiazhao:
			if (App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_LICENSE) == null || App.FUNCTION_CONFIG.get(Constant.Config.FUNCTION_LICENSE) != 1) {
				Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_LONG).show();
				return;
			}
			startActivity(new Intent(getActivity(), DriveSchoolActivity.class));
			break;
		case R.id.qr:
			startActivityForResult(new Intent(getActivity(), QRScanActivity.class), REQUESTCODE_QR);
			break;
		}
	}
	
	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		
	}

	@Override
	public void onPageSelected(int position) {
		// 取余后的索引
		int newPositon = position % imagelist.size();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == Activity.RESULT_OK){
			switch(requestCode){
			case REQUESTCODE_QR:
				String qrcode = data.getStringExtra("result");
				if(qrcode!=null&&qrcode.length()!=0&&qrcode.startsWith("clean:")){
					Toast.makeText(getActivity(), "扫描成功，正在进入洗车店", Toast.LENGTH_LONG).show();
					mCleanReq.setShopid(qrcode.replace("clean:", "")).postJsonRequest(getActivity(), mCleanHandler);
				}else{
					Toast.makeText(getActivity(), "扫描二维码失败", Toast.LENGTH_LONG).show();
				}
				break;
			}
		}
	}
	
	@Override
	public void onResponse(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if(res instanceof PromotionResponse){
			List<TPromotion> promotions = (((PromotionResponse) res).datas).datas;
			if(promotions==null||promotions.size()==0){
				return;
			}
			viewPager = (ViewPager) mContentView.findViewById(R.id.viewpager);
			LinearLayout ll = (LinearLayout) mContentView.findViewById(R.id.ll_point_group);

			imagelist = new ArrayList<ImageView>();

			ImageView iv;
			View view;
			LayoutParams params;
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity()).build();
			ImageLoader imageloader = ImageLoader.getInstance();
			imageloader.init(config);
			imagelist.clear();
			ll.removeAllViews();
			for (TPromotion data : promotions) {
				iv = new ImageView(getActivity());
				iv.setScaleType(ScaleType.CENTER_CROP);
				iv.setImageResource(R.drawable.bg_main_img);
				imagelist.add(iv);
				if(data.imgurl!=null&&data.imgurl.length()!=0&&!data.imgurl.startsWith("http")){
					data.imgurl = Constant.IMG_PREFIX+data.imgurl;
				}
				final TPromotion tmp = data;
				iv.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent i = new Intent(getActivity(), PromotionJoinActivity.class);
						i.putExtra("data", tmp);
						startActivity(i);
					}
				});
				if(data.imgurl!=null&&data.imgurl.length()!=0){
					imageloader.displayImage(data.imgurl, iv);
				}
//				App.loadImg(imagelist.get(i++), imageLoader, data.imgurl);

				// 每循环一次添加一个点到现形布局中
				view = new View(getActivity());
				params = new LayoutParams(5, 5);
				params.leftMargin = 5;
				view.setEnabled(false);
				view.setLayoutParams(params);
				ll.addView(view); // 向线性布局中添加“点”
			}

			viewPager.setAdapter(new MyAdapter());
			viewPager.setOnPageChangeListener(this);

			// 初始化图片描述和哪一个点被选中
			ll.getChildAt(0).setEnabled(true);
			// 初始化viewpager的默认position.MAX_value的一半
			int index = (Integer.MAX_VALUE / 2)
					- ((Integer.MAX_VALUE / 2) % imagelist.size());
//			viewPager.setCurrentItem(index); // 设置当前viewpager选中的pager页
			initImg();
		}else if(res instanceof CleanShopDetailResponse){
			Intent cleanIntent = new Intent(getActivity(), OrderCleanActivity.class);
			cleanIntent.putExtra("data", ((CleanShopDetailResponse) res).data);
			startActivity(cleanIntent);
		}
	}

	@Override
	public void onError(IResponseHandler classz) {
		
	}

	
	class MyAdapter extends PagerAdapter {

		/**
		 * 销毁对象
		 * 
		 * @param position
		 *            将要被销毁对象的索引位置
		 */
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			if(imagelist!=null&&imagelist.size()!=0){
				container.removeView(imagelist.get(position % imagelist.size()));
			}
		}

		/**
		 * 初始化一个对象
		 * 
		 * @param position
		 *            将要被创建的对象的索引位置
		 */
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if(imagelist==null||imagelist.size()==0){
				return null;
			}
			// 先把对象添加到viewpager中，再返回当前对象
			try{
				container.addView(imagelist.get(position % imagelist.size()));
			}catch(Exception e){
				System.out.println("--------position:" + position + " container="+container + " imagelist:"+imagelist +" imagelist.size: " + position);
			}
			return imagelist==null?null:imagelist.get(position % imagelist.size());
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return Integer.MAX_VALUE;
		}

		/**
		 * 复用对象 true 复用对象 false 用的是object
		 */
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}
	
}
